package cc.linker.steplink.crm.task;

import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.lock.RedisLock;
import cc.linker.steplink.crm.dao.SelfDao;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class NewsTask {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SelfDao selfDao;

    @Autowired
    private HttpService httpService;

    @Value("${system.scrm.wxpushurl}")
    private String url;

    @RedisLock("NewsTask_awakenTask")
    @Scheduled(cron = "10 */5 * * * ?")
    public void awakenTask() throws Exception {
        SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
        SimpleDateFormat sf2 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<HashMap<String, Object>> maps = selfDao.getValidTask();
        if (maps != null && maps.size() > 0) {
            for (HashMap<String, Object> item : maps) {
                String taskTimeKey = "task_send_time_"+item.get("TASK_ID");
                String timeVal = stringRedisTemplate.opsForValue().get(taskTimeKey);
                if(null == timeVal || "".equals(timeVal)){
                    String ss = sf.format((Time) item.get("SEND_TIME"));
                    Date startDate = ((Date) item.get("START_TIME"));
                    String overStartTime = sf2.format(startDate) + " " + ss;
                    Long startlong = sf3.parse(overStartTime).getTime() / 1000;
                    stringRedisTemplate.opsForValue().set(taskTimeKey,startlong.toString());
                    stringRedisTemplate.expireAt(taskTimeKey,sf3.parse(item.get("END_TIME").toString()));
                }
            }
        }
    }

    @RedisLock("NewsTask_sendNews")
    @Scheduled(cron = "10 */5 * * * ?")
    public void sendNews() throws Exception {
        Long nowtime = new Date().getTime() / 1000;
        SimpleDateFormat sf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Set<String> keyList = stringRedisTemplate.keys("task_send_time_*");
        if(keyList instanceof Set){
            for (String key:keyList){
                String val = stringRedisTemplate.opsForValue().get(key);
                if(Long.parseLong(val) < nowtime){
                    key.substring(key.indexOf("task_send_time_"));
                    HashMap<String,Object> taskInfo = selfDao.getTaskOne(key.substring(15));
                    //没有这条任务，continue
                    if(taskInfo == null){
                        continue;
                    }
                    String groupId = taskInfo.get("GROUP_ID").toString();
                    List<HashMap<String, Object>> personList = selfDao.getNeedPushUserListByGroupId(groupId);
                    HashMap<String,Object> artInfo = selfDao.getTaskArticleOne(key.substring(15));
                    //没有人或没有新闻，continue
                    if(personList == null || artInfo == null){
                        continue;
                    }
                    selfDao.updateAwakenArticlesState(key.substring(15), artInfo.get("ARTICLE_ID").toString());

                    Map<String, Object> pushdata = new HashMap<String, Object>();
                    for (HashMap<String, Object> per : personList) {
                        if (per == null) {
                            continue;
                        }
                        if (null == per.get("WX_TOKEN") || "".equals(per.get("WX_TOKEN"))) {
                            continue;
                        }
                        if (null == per.get("WX_OPENID") || "".equals(per.get("WX_OPENID"))) {
                            continue;
                        }
                        pushdata.put("action", "replayNews");
                        pushdata.put("token", per.get("WX_TOKEN").toString());
                        pushdata.put("openid", per.get("WX_OPENID").toString());
                        pushdata.put("title", artInfo.get("ARTICLE_TITLE"));
                        pushdata.put("desc", artInfo.get("ARTICLE_DESC"));
                        pushdata.put("url", artInfo.get("ARTICLE_URL"));
                        pushdata.put("image", artInfo.get("ARTICLE_IMAGE"));

                        Map<String, String> postParam = new HashMap<>();
                        postParam.put("Content-Type", "application/json;charset=UTF-8");
                        JSONObject jsonObject = (JSONObject) JSONArray.toJSON(pushdata);
                        Object postres = httpService.doPost(url,jsonObject.toJSONString(),postParam);
//                        Object postres = CallService.jsonPost(url,jsonObject.toJSONString());
                        System.out.println(postres);
                    }
                    //更新下次发送时间
                    Long nextSendTime = Long.parseLong(val)+Long.parseLong(taskInfo.get("INTERVAL_TIME").toString());
                    stringRedisTemplate.opsForValue().set(key,nextSendTime.toString());
                    stringRedisTemplate.expireAt(key,sf3.parse(taskInfo.get("END_TIME").toString()));
                }

            }
        }
    }
}
